from time import *
import os

def timestamp_string(seconds):
    timetupple=gmtime(seconds)

    return '%(day)02d.%(month)02d.%(year)02d %(hour)02d:%(minute)02d:%(second)02d' %{'day':timetupple[2],'month':timetupple[1],'year':timetupple[0]%100,'hour':timetupple[3],'minute':timetupple[4],'second':timetupple[5]}


def timestamp_obfuscated(seconds):
    timetupple=gmtime(seconds)
    caesar={'0':'1','1':'2','2':'3','3':'4','4':'5','5':'6','6':'7','7':'8','8':'9','9':'0'}

    timestring='%(day)02d%(month)02d%(year)02d%(hour)02d%(minute)02d%(second)02d' %{'day':timetupple[2],'month':timetupple[1],'year':timetupple[0]%100,'hour':timetupple[3],'minute':timetupple[4],'second':timetupple[5]}
    result=""

    for char in timestring:
        result=result+caesar[char]

    return result

def get_timestamp_by_filename(filename):
    """
    Extract timestamp from passed file.
    """
    if os.path.basename(filename)!='timeh.h':
        return get_timestamp_obfuscated(filename)
    else:
        try:
            infile=file(filename)
            for line in infile:
                if line.find('KeyLinkTime')!=-1:
                    return line[line.index('"')+1:line.index('"')+13]
            return None
        except:
            return None

def get_timestamp_obfuscated(filename):
        try:
                infile=file(filename)
                for line in infile:
                        if line.find('TIMESTAMP_OBFUSCATED')!=-1:
                                line=line[line.index('"')+1:]
                                return line[:line.index('"')]
                return None
        except:
                return None

def get_timestamp_numeric(filename):
        try:
                infile=file(filename)
                for line in infile:
                        searchstr='TIMESTAMP_NUMERIC'
                        if line.find(searchstr)!=-1:
                                line=line[line.find(searchstr)+len(searchstr):].strip()
                                if line.endswith('UL'):
                                    line=line[:-2]
                                if line.startswith('0x'):
                                    return int(line,16)
                                else:
                                    return int(line)
                return None
        except:
                return None


def get_timestamp_backup_string(timestamp, version, dispatchpath):
        lt=localtime(get_timestamp_numeric(timestamp))
        swid=get_timestamp_obfuscated(timestamp)
        datestr=strftime('%Y.%m.%d', lt)
        try:
            st_filename=os.path.join(dispatchpath, swid+'.symtab')
            symfile = open(st_filename, mode='r')
        except:
            st_filename=os.path.join(dispatchpath, 'tmp', swid+'.symtab')
            symfile = open(st_filename, mode='r')
        st=symtab.read_symtab(symfile)

        try:
            pv=st['version::ProgramVers']['thisvers']
        except:
            pv=None
        try:
            dv=st['version::DiagVers']['thisvers']
        except:
            dv=None
        rv = '@echo off\n'
        rv+= 'rem automatic generated file (by Tools/timestamp.py), do not edit\n \n'
        rv+= 'set dirname='+datestr+'__ID'+str(swid)+'__PV_'+str(pv)+'__DV_'+str(dv)+'\n'
        rv+= 'set ID='+swid
        return rv


def timestamp_numeric(seconds):
    return hex(seconds)+"UL"

def timestamp_header( seconds ):
    return '''
/**
*  \\file timestamp.h
*
*  \\brief Time Stamp
*
*  \\author  Michael J. Hohmann <michael.hohmann@linde-mh.de>
*
*  Timestamp generatated at:
*  '''+asctime(gmtime(seconds))+''' UTC  (a.k.a GMT)
*
*/

#ifndef TIMESTAMP_H_INCLUDED
#define TIMESTAMP_H_INCLUDED

#ifdef __cplusplus
   extern "C" {
#endif


/*================================================[ public includes  ]================================================*/

/** Timestamp as numerical value.
*
*  In seconds since 01.01.1970 UTC.
*/
#define TIMESTAMP_NUMERIC       '''+timestamp_numeric(seconds)+'''

/** Timestamp String.
*
*  Timestamp as 17 character null terminated string with syntax "dd.mm.yy hh:mm:ss".
*/
#define TIMESTAMP_STRING        "'''+timestamp_string(seconds)+'''"

/** Obfuscated Timestamp.
*
*
* #define TIMESTAMP_OBFUSCATED    "'''+timestamp_obfuscated(seconds)+'''"
*/

char software_id[] = "'''+timestamp_obfuscated(seconds)+'''";

/*====================================================================================================================*/

#ifdef __cplusplus
   }
#endif

#endif

/***********************************************************************************************************************
*                             Copyright 2007 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/
'''




if __name__=="__main__":
    filename=open('timestamp.h','w'); 
    gmt=int(time())
    print>>filename,timestamp_header(gmt)


